﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebUI.Models;
using Beauty.BLL;
using Beauty.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WebUI.Areas.API.Controllers
{
    public class APPInterFaceController : Controller
    {
        // GET: API/APPInterFace

        UtilWebService util = new UtilWebService();
        base_tokenBLL base_tokenBll = new base_tokenBLL();
        System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        collectionBLL collectBll = new collectionBLL();
        base_dicBLL dicBll = new base_dicBLL();
        feedbackBLL feedbackBll = new feedbackBLL();
        picalbumBLL albumBll = new picalbumBLL();
        #region 获取分类
        public ActionResult GetAllClassify()
        {
            List<picclass> list = util.GetAllAlbumClass();

            var data = from c in list
                       select new
                       {
                           ClassName = c.ClassName,
                           Id = c.ClassId,
                           AddTime = Convert.ToDateTime(c.AddTime).ToString("yyyy-MM-dd HH:mm:ss"),
                           PinYin = c.PinYin,
                           SortId = c.SortId,
                           UpdateTime = Convert.ToDateTime(c.UpdateTime).ToString("yyyy-MM-dd HH:mm:ss"),
                       };
            ResData res = new ResData()
            {
                resCode = 200,
                resMsg = "获取成功",
                resData = jss.Serialize(data),
            };


            return MyJson(res);
        }

        #endregion
        #region 获取套图列表
        public ActionResult GetAlbumsList()
        {
            //请求案列 /API/GetAlbumsList?reqData="{"pinyin":"tuijian"}"
            ResData res;
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON


            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);


            string pinyinOfAlbum = o["pinyin"].ToString();
            int pageIndex = Convert.ToInt32(o["pageIndex"].ToString());
            if (!Checking(pinyinOfAlbum, out res))
            {
                return MyJson(res);
            }
            List<picclass> list = util.GetAllAlbumClass();
            string selected;
            List<picalbum> albums = util.GetAlbumsByAction(pinyinOfAlbum, list, out selected, true, pageIndex);
            if (albums == null)
            {
                res.resCode = 201;
                res.resMsg = "分类不存在";
                return MyJson(res);
            }
            if (albums.Count < 1)
            {
                res.resMsg = "此分类下没有套图";
            }
            var data = from a in albums
                       select new
                       {
                           AlbumId = a.AlbumId,
                           Title = a.Title,
                           Description = a.Description,
                           CoverSrc = a.CoverSrc,
                           AddTime = Convert.ToDateTime(a.AddTime).ToString("yyyy-MM-dd HH:mm:ss"),
                           UpdateTime = Convert.ToDateTime(a.UpdateTime).ToString("yyyy-MM-dd HH:mm:ss"),
                           ClassId = a.ClassId,
                       };
            res.resData = jss.Serialize(data);
            res.resCode = 200;
            return MyJson(res);
        }

        #endregion
        #region 获取套图详情
        public ActionResult GetAlbumsDetial()
        {
            //请求案列 /API/GetAlbumsDetial?reqData="{"albumid":"1"}"
            ResData res = new ResData() { resMsg = "获取成功" };
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON


            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);


            int albumId;
            if (!int.TryParse(o["albumid"].ToString(), out albumId))
            {
                res.resCode = 202;
                res.resMsg = "请输入正确";
                return MyJson(res);
            }

            List<picmain> mains;
            List<picalbum> Recommends;
            picalbum album;
            picclass picclass;
            util.GetAlbumDetialData(albumId, out mains, out Recommends, out picclass, out album);
            if (album == null)
            {
                res.resCode = 201;
                res.resMsg = "套图不存在";
                return MyJson(res);
            }
            var data1 = from m in mains
                        select new
                        {
                            PicId = m.PicId,
                            Src = m.Src,
                            AddTime = Convert.ToDateTime(m.AddTime).ToString("yyyy-MM-dd HH:mm:ss"),
                            UpdateTime = Convert.ToDateTime(m.UpdateTime).ToString("yyyy-MM-dd HH:mm:ss"),
                        };
            var data2 = from a in Recommends
                        select new
                        {
                            AlbumId = a.AlbumId,
                            Title = a.Title,
                            Description = a.Description,
                            CoverSrc = a.CoverSrc,
                            AddTime = Convert.ToDateTime(a.AddTime).ToString("yyyy-MM-dd HH:mm:ss"),
                            UpdateTime = Convert.ToDateTime(a.UpdateTime).ToString("yyyy-MM-dd HH:mm:ss"),
                            ClassId = a.ClassId,
                        };
            var responseData = new { ClassName = picclass.ClassName, AlbumTitle = album.Title, Pictures = data1, RecommentsAlbums = data2 };

            if (mains.Count > 0)
            {
                res.resCode = 200;
                res.resData = jss.Serialize(responseData);
            }
            else
            {
                res.resMsg = "此套图下没有图片";
            }
            return MyJson(res);

        }

        #endregion
        userBLL bllUser = new userBLL();
        #region 注册接口
        public ActionResult Register()
        {

            string mobile, pwd;
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            mobile = o["mobile"].ToString();
            pwd = o["pwd"].ToString();
            ResData res = new ResData();
            user userAfterReg;
            List<user> user = bllUser.GetModelList("UMobile='" + mobile + "'");
            if (user.Count > 0)
            {
                res.resCode = 201;
                res.resMsg = "该手机号已被占用";
            }
            else
            {
                //if (Session[DataConfig.VerifyCode].ToString() == code)
                //{

                bool flag = bllUser.Add(new Beauty.Model.user()
                {
                    UPass = pwd,
                    UMobile = mobile,
                    IconUrl = "/Pic/user_headimg/img_default_avatar.png"
                });
                if (flag)
                {
                    //注册成功  1、保存用户token 
                    bllUser.Login(mobile, pwd, mobile, out userAfterReg, res);
                    base_token userToken = new base_token()
                    {
                        Token = Guid.NewGuid().ToString(),
                        Uid = userAfterReg.Uid,
                        Timeout = DateTime.Now.AddMonths(1),
                    };

                    if (!base_tokenBll.Add(userToken))
                    {
                        res.resCode = 202;
                        res.resMsg = "token添加失败";
                        return MyJson(res);
                    }
                    var responseData = new
                    {
                        uid = userAfterReg.Uid,
                        uname = userAfterReg.UName,
                        umobile = userAfterReg.UMobile,
                        uemail = userAfterReg.UEmail,
                        nickname = userAfterReg.NickName,
                        regtime = Convert.ToDateTime(userAfterReg.RegTime).ToString("yyyy-MM-dd HH:mm:ss"),
                        IconUrl = userAfterReg.IconUrl,
                        UserToken = userToken.Token
                    };
                    res.resData = jss.Serialize(responseData);
                    res.resCode = 200;
                    res.resMsg = "注册成功";

                }
                else
                {
                    res.resCode = 201;
                    res.resMsg = "注册失败，请重试";
                }
                //}
                //else
                //{
                //    res.resCode = 202;
                //    res.resMsg = "验证码不正确";

                //}
            }
            return MyJson(res);
        }


        #endregion
        //日期处理正常，图片路径处理为绝对路径
        #region 登录接口
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            ResData res = new ResData() { resMsg = "获取成功" };
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            string mobile, pwd;

            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            mobile = o["mobile"].ToString();
            pwd = o["pwd"].ToString();
            user user;
            if (!bllUser.Login(mobile, pwd, mobile, out user, res))
            {
                return MyJson(res);
            }

            //生成token前首先判断这个用户的token是否已经存在,并且这个token没有过期
            base_token userToken;
            List<base_token> tokens = base_tokenBll.GetModelList("Uid=" + user.Uid);
            ResData resToken;
            if (tokens.Count > 0)
            {
                if (Convert.ToDateTime(tokens[0].Timeout).Subtract(DateTime.Now).TotalHours > 0)
                {
                    userToken = tokens[0];
                }
                else
                {
                    if (!AddToken(out userToken, user, out resToken))
                    {
                        return MyJson(resToken);
                    }

                }
            }
            else
            {

                if (!AddToken(out userToken, user, out resToken))
                {
                    return MyJson(resToken);
                }
            }



            var responseData = new
            {
                uid = user.Uid,
                uname = user.UName,
                umobile = user.UMobile,
                uemail = user.UEmail,
                nickname = user.NickName,
                regtime = Convert.ToDateTime(user.RegTime).ToString("yyyy-MM-dd HH:mm:ss"),
                IconUrl = user.IconUrl,
                UserToken = userToken.Token
            };
            if (res.resCode == 200)
            {
                res.resData = jss.Serialize(responseData);
            }
            return MyJson(res);

        }
        public bool AddToken(out base_token userToken, user user, out ResData res)
        {
            res = new ResData();
            userToken = new base_token()
            {
                Token = Guid.NewGuid().ToString(),
                Uid = user.Uid,
                Timeout = DateTime.Now.AddMonths(1),
            };
            List<base_token> tokens = base_tokenBll.GetModelList("Uid=" + user.Uid);
            //添加用户token之前，先删除之前的
            foreach (var item in tokens)
            {
                base_tokenBll.Delete(item.Token);
            }
            if (!base_tokenBll.Add(userToken))
            {
                res.resCode = 202;
                res.resMsg = "token添加失败";
                return false;
            }
            return true;
        }
        #endregion

        #region 收藏接口
        public ActionResult AddCollect()
        {
            ResData res = new ResData();
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            int albumId = Convert.ToInt32(o["albumId"]);
            string token = Request.Headers["token"];
            base_token userToken;
            if (!CheckToken(token, out userToken, out res))
            {
                return MyJson(res);
            }
            else
            {
                if (albumBll.GetModel(albumId) == null)
                {
                    res.resCode = 201;
                    res.resMsg = "套图不存在";
                    return MyJson(res);
                }
                if (CommonMethod.IsCollect((int)userToken.Uid, albumId))
                {
                    res.resCode = 201;
                    res.resMsg = "该套图已收藏";
                    return MyJson(res);
                }
                //不为空则去验证token的合法性
                if (CommonMethod.AddCollection((int)userToken.Uid, albumId))
                {
                    res.resCode = 200;
                    res.resMsg = "收藏成功";
                }
                else
                {
                    res.resCode = 201;
                    res.resMsg = "收藏失败";
                }
                return MyJson(res);
            }

        }
        #endregion
        #region 取消收藏接口
        public ActionResult DelCollect()
        {
            ResData res = new ResData();
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            int albumId = Convert.ToInt32(o["albumId"]);
            string token = Request.Headers["token"];
            base_token userToken;
            if (!CheckToken(token, out userToken, out res))
            {
                return MyJson(res);
            }
            else
            {
                if (albumBll.GetModel(albumId) == null)
                {
                    res.resCode = 201;
                    res.resMsg = "套图不存在";
                    return MyJson(res);

                }
                //不为空则去验证token的合法性
                if (CommonMethod.RemoveCollection((int)userToken.Uid, albumId))
                {
                    res.resCode = 200;
                    res.resMsg = "取消收藏成功";
                }
                else
                {
                    res.resCode = 201;
                    res.resMsg = "取消收藏失败";
                }
                return MyJson(res);
            }

        }
        #endregion
        #region 获取APP版本号

        public ActionResult GetVersion()
        {
            List<base_dic> list = dicBll.GetModelList(" 1=1");
            base_dic version = list.Where<base_dic>(d => d.DicName == "版本号").FirstOrDefault();
            base_dic down = list.Where<base_dic>(d => d.DicName == "下载地址").FirstOrDefault();
            var data = new { ver = version.DicValue, downUrl = down.DicValue };
            ResData res = new ResData()
            {
                resCode = 200,
                resMsg = "获取成功",
                resData = JsonConvert.SerializeObject(data),
            };
            return MyJson(res);
        }
        #endregion
        #region 反馈
        public ActionResult FeedBack()
        {
            ResData res = new ResData() { resMsg = "获取成功" };
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            string content, contacts;

            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            content = o["content"].ToString();
            contacts = o["contacts"].ToString();
            string token = Request.Headers["token"];
            base_token userToken;
            feedback entity;
            if (!CheckToken(token, out userToken, out res))
            {
                //游客
                entity = new feedback()
                {
                    AddTime = DateTime.Now,
                    Contacts = contacts,
                    Content = content,
                };
            }
            else
            {
                //登录用户
                entity = new feedback()
                {
                    AddTime = DateTime.Now,
                    Contacts = contacts,
                    Content = content,
                    Uid = userToken.Uid
                };
            }
            if (feedbackBll.Add(entity))
            {
                res.resCode = 200;
                res.resMsg = "成功";

            }
            else
            {
                res.resCode = 201;
                res.resMsg = "失败，请重试";
            }
            return MyJson(res);
        }
        #endregion
        public int PageSize { get { return 10; } }
        #region 获取收藏
        public ActionResult GetCollect()
        {
            ResData res = new ResData();
            string reqData = Request.Form["reqData"];
            if (string.IsNullOrEmpty(reqData))
            {
                reqData = "";
            }
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            int pageIndex;
            if (o != null)
            {
                pageIndex = Convert.ToInt32(o["pageIndex"].ToString());
            }
            else
            {
                pageIndex = 1;
            }
            pageIndex = (pageIndex - 1) * PageSize;

            string token = Request.Headers["token"];

            base_token userToken;
            if (!CheckToken(token, out userToken, out res))
            {
                return MyJson(res);
            }
            else
            {
                List<collection> list = util.GetCollectionByUid((int)userToken.Uid, pageIndex, PageSize);
                res.resCode = 200;
                res.resMsg = "获取成功";
                res.resData = JsonConvert.SerializeObject(list);
                return MyJson(res);
            }
        }
        #endregion
        #region QQ登录接口
        public ActionResult QQLogin()
        {
            ResData res = new ResData() { resMsg = "获取成功" };
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            string openid, nickname, figureurl;

            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            openid = o["openid"].ToString();
            nickname = o["nickname"].ToString();
            figureurl = o["figureurl"].ToString();
            //查询qq与用户是否关联了，没有关联的话，就是首次注册，否则返回用户信息
            List<user> temp = bllUser.GetModelList("qqOpenId='" + openid + "'");
            user user;
            if (temp.Count > 0)
            {
                //已经绑定
                user = temp[0];
            }
            else
            {
                //首次注册
                user = new user()
                {
                    UName = nickname,
                    IconUrl = figureurl,
                    qqOpenId = openid,
                    NickName = nickname,
                    RegTime = DateTime.Now,
                };
                bllUser.Add(user);
                //插入后 重新查询以获取到最新的ID
                user = bllUser.GetModelList("qqOpenId='" + openid + "'")[0];
            }

            //生成token前首先判断这个用户的token是否已经存在,并且这个token没有过期
            base_token userToken;
            List<base_token> tokens = base_tokenBll.GetModelList("Uid=" + user.Uid);
            ResData resToken;
            if (tokens.Count > 0)
            {
                if (Convert.ToDateTime(tokens[0].Timeout).Subtract(DateTime.Now).TotalHours > 0)
                {
                    userToken = tokens[0];
                }
                else
                {
                    if (!AddToken(out userToken, user, out resToken))
                    {
                        return MyJson(resToken);
                    }

                }
            }
            else
            {

                if (!AddToken(out userToken, user, out resToken))
                {
                    return MyJson(resToken);
                }
            }
            var responseData = new
            {
                uid = user.Uid,
                uname = user.UName,
                umobile = user.UMobile,
                uemail = user.UEmail,
                nickname = user.NickName,
                regtime = Convert.ToDateTime(user.RegTime).ToString("yyyy-MM-dd HH:mm:ss"),
                IconUrl = user.IconUrl,
                UserToken = userToken.Token
            };
            res.resData = JsonConvert.SerializeObject(responseData);

            return MyJson(res);
        }
        #endregion
        #region 上传头像接口
        public ActionResult UploadHead()
        {
            ResData res = new ResData();
            //string reqData = Request.Form["reqData"];
            //string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            //JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            string token = Request.Headers["token"];
            base_token userToken;
            if (!CheckToken(token, out userToken, out res))
            {
                return MyJson(res);
            }
            else
            {
                user user = bllUser.GetModel((int)userToken.Uid);
                res = util.Upload(user);
                return MyJson(res);
            }

        }
        #endregion
        #region 修改密码接口
        public ActionResult ChangePass()
        {
            ResData res = new ResData();
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            string mobile = o["mobile"].ToString();
            string newpass = o["newpass"].ToString();
            List<user> list = bllUser.GetModelList(" UMobile='" + mobile + "'");
            if (list.Count > 0)
            {
                user user = list[0];
                res = util.ChangePass(user, user.UPass, newpass);

            }
            else
            {
                res.resCode = 201;
                res.resMsg = "用户不存在";
            }
            return MyJson(res);


        }
        #endregion
        #region 修改其他用户信息接口
        public ActionResult ChangeUser()
        {
            ResData res = new ResData();
            string reqData = Request.Form["reqData"];
            string normal_reqData = Decrypt(reqData);//这里解密下请求过来的参数 解密后是一个JSON
            JObject o = (JObject)JsonConvert.DeserializeObject(normal_reqData);
            string token = Request.Headers["token"];
            base_token userToken;
            if (!CheckToken(token, out userToken, out res))
            {
                return MyJson(res);
            }
            else
            {
                string nickname = o["nickname"].ToString();
                user user = bllUser.GetModel((int)userToken.Uid);
                user.NickName = nickname;
                if (bllUser.Update(user))
                {
                    res.resCode = 200;
                    res.resMsg = "修改成功";
                }
                else
                {
                    res.resCode = 201;
                    res.resMsg = "修改失败";
                }
                return MyJson(res);
            }

        }
        #endregion

        private bool CheckToken(string token, out base_token userToken, out ResData res)
        {
            res = new ResData();
            userToken = null;
            if (string.IsNullOrEmpty(token))
            {
                res.resCode = 202;
                res.resMsg = "token为空";
                return false;
            }
            else
            {
                //不为空则去验证token的合法性
                userToken = base_tokenBll.GetModel(token);
                if (userToken == null || Convert.ToDateTime(userToken.Timeout).Subtract(DateTime.Now).TotalHours < 1)
                {
                    res.resCode = 202;
                    res.resMsg = "token无效";
                    return false;
                }
                return true;
            }
        }
        private bool Checking(string value, out ResData res)
        {
            if (string.IsNullOrEmpty(value))
            {
                res = new ResData() { resMsg = "error", resCode = 203 };
                return false;
            }
            res = new ResData() { resMsg = "获取成功" };
            return true;
        }

        private string Encrypt(string data)
        {
            return data;
        }
        private string Decrypt(string data)
        {
            return data;
        }

        private JsonResult MyJson(object data)
        {
            return Json(data, JsonRequestBehavior.DenyGet);
        }
    }
}